package edu.nf.supermarket.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author yjj
 * @date 2025-05-19
 */
@Configuration
@MapperScan("edu.nf.supermarket.mapper")
@EnableTransactionManagement
public class MybatisConfig {
    /**
     * 配置Druid连接池数据源
     *
     * @return
     */
    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() throws Exception {
        Properties prop = new Properties();
        InputStream is = MybatisConfig.class.getClassLoader().getResourceAsStream("druid.properties");
        prop.load(is);
        return (DruidDataSource) DruidDataSourceFactory.createDataSource(prop);
    }
    /**
     * 装配SqlSessionFactorybean, 用于将SqlSessionFactory
     * 安如如IoC容器中管理
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //注入数据源
        ssfb.setDataSource(dataSource());
        //设置实体的别名
        ssfb.setTypeAliasesPackage("edu.nf.ssm.entity");
        //设置mapper映射配置文件路径
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        ssfb.setMapperLocations(resolver.getResources("classpath:mappers/*.xml"));
        //配置分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        //设置分页属性
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("reasonable", "true");
        pageInterceptor.setProperties(properties);
        //将分页拦截器添加到插件中
        ssfb.setPlugins(pageInterceptor);
        //启用sql日志（将日志直接输入到控制台）
        org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();
        conf.setLogImpl(StdOutImpl.class);
        ssfb.setConfiguration(conf);
        return ssfb;
    }
    /**
     * 装配事务管理器
     */
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
